#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/kdev_t.h>
#include <linux/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/types.h>
#include <linux/ioctl.h>

MODULE_LICENSE("GPL");

typedef struct Scull_Dev {
    void **data;
    struct Scull_Dev *next;   /* next listitem */
    int quantum;              /* the current quantum size */
    int qset;                 /* the current array size */
    unsigned long size;
    unsigned int access_key;  /* used by sculluid and scullpriv */
    struct semaphore sem;     /* mutual exclusion semaphore     */
    struct cdev cdev;	  /* Char device structure		*/
} Scull_Dev;

#ifndef SCULL_QUANTUM
#define SCULL_QUANTUM 4000
#endif

#ifndef SCULL_QSET
#define SCULL_QSET    1000
#endif

#ifndef SCULL_MAJOR
#define SCULL_MAJOR 0   /* dynamic major by default */
#endif

#ifndef SCULL_NR_DEVS
#define SCULL_NR_DEVS 4    /* scull0 through scull3 */
#endif

#ifndef SCULL_P_NR_DEVS
#define SCULL_P_NR_DEVS 4  /* scullpipe0 through scullpipe3 */
#endif


int scull_major =   SCULL_MAJOR;
int scull_minor =   0;
int scull_nr_devs = SCULL_NR_DEVS;    /* number of bare scull devices */
int scull_quantum = SCULL_QUANTUM;
int scull_qset =    SCULL_QSET;
/*
 * Ioctl definitions
 */

/* Use 'K' as magic number */
#define SCULLC_IOC_MAGIC  'K'

#define SCULLC_IOCRESET    _IO(SCULLC_IOC_MAGIC, 0)

/*
 * S means "Set" through a ptr,
 * T means "Tell" directly
 * G means "Get" (to a pointed var)
 * Q means "Query", response is on the return value
 * X means "eXchange": G and S atomically
 * H means "sHift": T and Q atomically
 */
#define SCULLC_IOCSQUANTUM _IOW(SCULLC_IOC_MAGIC,  1, __u32)
#define SCULLC_IOCTQUANTUM _IO(SCULLC_IOC_MAGIC,   2)
#define SCULLC_IOCGQUANTUM _IOR(SCULLC_IOC_MAGIC,  3, __u32)
#define SCULLC_IOCQQUANTUM _IO(SCULLC_IOC_MAGIC,   4)
#define SCULLC_IOCXQUANTUM _IOWR(SCULLC_IOC_MAGIC, 5, __u32)
#define SCULLC_IOCHQUANTUM _IO(SCULLC_IOC_MAGIC,   6)
#define SCULLC_IOCSQSET    _IOW(SCULLC_IOC_MAGIC,  7, __u32)
#define SCULLC_IOCTQSET    _IO(SCULLC_IOC_MAGIC,   8)
#define SCULLC_IOCGQSET    _IOR(SCULLC_IOC_MAGIC,  9, __u32)
#define SCULLC_IOCQQSET    _IO(SCULLC_IOC_MAGIC,  10)
#define SCULLC_IOCXQSET    _IOWR(SCULLC_IOC_MAGIC,11, __u32)
#define SCULLC_IOCHQSET    _IO(SCULLC_IOC_MAGIC,  12)

#define SCULLC_IOCHARDRESET _IO(SCULLC_IOC_MAGIC, 13) /* debugging tool */

#define SCULLC_IOC_MAXNR 13


Scull_Dev *scull_devices; /* allocated in scull_init_module */
static DECLARE_WAIT_QUEUE_HEAD(wq);
static int flag=0;
static struct class *scull_class = NULL;
static struct device **scull_device_fsys = NULL;

#define SCULLC_USE_PROC
#ifdef SCULLC_USE_PROC

void scullc_proc_offset(char *buf, char **start, off_t *offset, int *len)
{
    if (*offset == 0) {
        return;
    }

    if (*offset >= *len) {
        *offset -= *len;
        *len = 0;
    } else
    {
        *start = buf + *offset;
        *offset = 0;
    }
    
}
static void *scull_seq_start(struct seq_file *s, loff_t *pos)
{
    if (*pos >= scull_nr_devs) {
        return NULL;
    }

    return scull_devices + *pos;
}

static void *scull_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
    (*pos)++;
    if (*pos >= scull_nr_devs) {
        return NULL;
    }

    return scull_devices + *pos;
}

static void scull_seq_stop(struct seq_file *s, void *v)
{
    return;
}

static int scull_seq_show(struct seq_file *s, void *v)
{
    struct Scull_Dev *dev = (struct Scull_Dev*)v;
    struct Scull_Dev *dptr, *next;
    int qset, i;

    if (down_interruptible(&dev->sem)) {
        return -ERESTARTSYS;
    }
    seq_printf(s, "\nDevice %i: qset %i, q %i, sz %li\n",
        (int)(dev - scull_devices), dev->qset, dev->quantum, dev->size);
    for (dptr = dev; dptr; dptr = next){
        qset = dptr->qset;
        seq_printf(s, "item at %p, qset at %p\n", dptr, dptr->data);
        if (dptr->data && !dptr->next) {
            if (dptr->data[i])
            seq_printf(s, " %4i:%p\n", i, dptr->data[i]);
        }
        next = dptr->next;
    }
    return 0;
}
static struct seq_operations scull_seq_ops = {
    .start = scull_seq_start,
    .next = scull_seq_next,
    .stop = scull_seq_stop,
    .show = scull_seq_show
};

static int scull_proc_open(struct inode *inode, struct file *file)
{
    return seq_open(file, &scull_seq_ops);
}
struct file_operations scullc_proc_fops = {
    .owner = THIS_MODULE,
    .open = scull_proc_open,
    .read = seq_read,
    .llseek = seq_lseek,
    .release = seq_release
};

#endif  //SCULLC_USE_PROC
int scull_trim(Scull_Dev *dev)
{
    Scull_Dev *next, *dptr;
    int qset;
    int i;

	qset = dev->qset;
    for (dptr = dev; dptr; dptr = next) {
		if (dptr->data) {
			for (i = 0; i < qset; i++) {
			if (dptr->data[i]) {
					kfree(dptr->data[i]);
				}
			}
			kfree(dptr->data);
			dptr->data = NULL;
		}
		next = dptr->next;
		if (dptr != dev) {
			kfree(dptr);
		}
    }
	dev->size = 0;
	dev->quantum = scull_quantum;
	dev->qset = scull_qset;
	dev->next = NULL;
    return 0;
}
static void __exit scull_cleanup_module(void)
{
	int i;
	dev_t devno = MKDEV(scull_major, scull_minor);
	/* Get rid of our char dev entries */
	if (scull_devices) {
		for (i = 0; i < scull_nr_devs; i++) {
			scull_trim(scull_devices+i);
			cdev_del(&scull_devices[i].cdev);
            device_destroy(scull_class, MKDEV(scull_major, scull_minor + i));
		}
		kfree(scull_devices);
        if (scull_device_fsys) {
            kfree(scull_device_fsys);
            scull_device_fsys = NULL;
        }
	}

	/* cleanup_module is never called if registering failed */
	unregister_chrdev_region(devno, scull_nr_devs);
    class_destroy(scull_class);
#ifdef SCULLC_USE_PROC
    remove_proc_entry("scullcmem", 0);
#endif

    printk(KERN_DEBUG "goodbye world.\n");
}
/*
 * Open and close
 */

int scull_open(struct inode *inode, struct file *filp)
{
	Scull_Dev *dev; /* device information */

	dev = container_of(inode->i_cdev, Scull_Dev, cdev);
	filp->private_data = dev; /* for other methods */

	/* now trim to 0 the length of the device if open was write-only */
	if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
		if (down_interruptible(&dev->sem))
			return -ERESTARTSYS;
		scull_trim(dev); /* ignore errors */
		up(&dev->sem);
	}
	return 0;          /* success */
}

int scull_release(struct inode *inode, struct file *filp)
{
	return 0;
}

/*
 * Follow the list 
 */
Scull_Dev *scull_follow(Scull_Dev *dev, int n)
{
    while (n--) {
        if (!dev->next) {
            dev->next = kmalloc(sizeof(Scull_Dev), GFP_KERNEL);
            memset(dev->next, 0, sizeof(Scull_Dev));
        }
        dev = dev->next;
        continue;
    }
    return dev;
}
/*
 * Data management: read and write
 */

ssize_t scull_read(struct file *filp, char *buf, size_t count,
                loff_t *f_pos)
{
    Scull_Dev *dev = filp->private_data; /* the first listitem */
    Scull_Dev *dptr;
    int quantum = dev->quantum;
    int qset = dev->qset;
    int itemsize = quantum * qset; /* how many bytes in the listitem */
    int item, s_pos, q_pos, rest;
    ssize_t ret = 0;
    if (down_interruptible(&dev->sem))
        return -ERESTARTSYS;
    if (*f_pos >= dev->size){
        up(&dev->sem);
        printk(KERN_DEBUG "read buffer is empty.\n");
        wait_event_interruptible(wq, flag != 0);
        flag = 0;
        return ret;
    }
    if (*f_pos + count > dev->size)
        count = dev->size - *f_pos;
    /* find listitem, qset index, and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum;
	q_pos = rest % quantum;

    /* follow the list up to the right position (defined elsewhere) */
    dptr = scull_follow(dev, item);
    if (!dptr->data)
        goto out; /* don't fill holes */
    if (!dptr->data[s_pos])
        goto out;
    /* read only up to the end of this quantum */
    if (count > quantum - q_pos)
        count = quantum - q_pos;

    if (copy_to_user(buf, dptr->data[s_pos]+q_pos, count)) {
        ret = -EFAULT;
	goto out;
    }
    *f_pos += count;
    ret = count;

out:
    up(&dev->sem);
    return ret;
}

ssize_t scull_write(struct file *filp, const char *buf, size_t count,
                loff_t *f_pos)
{
    Scull_Dev *dev = filp->private_data;
    Scull_Dev *dptr;
    int quantum = dev->quantum;
    int qset = dev->qset;
    int itemsize = quantum * qset;
    int item, s_pos, q_pos, rest;
	ssize_t ret = -ENOMEM; /* value used in "goto out" statements */

    /* find listitem, qset index and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum;
	q_pos = rest % quantum;

    if (down_interruptible(&dev->sem))
            return -ERESTARTSYS;

    /* follow the list up to the right position */
    dptr = scull_follow(dev, item);
    if (!dptr->data) {
        dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
        if (!dptr->data)
            goto out;;
        memset(dptr->data, 0, qset * sizeof(char *));
    }
    if (!dptr->data[s_pos]) {
        dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
        if (!dptr->data[s_pos])
            goto out;;
    }
    if (copy_from_user(dptr->data[s_pos]+q_pos, buf, count)) {
        ret = -EFAULT;
	goto out;
    }
    *f_pos += count;
    ret = count;

    /* update the size */
    if (dev->size < (*f_pos)) {
		dev->size = *f_pos;
	}
    flag = 1;
    wake_up_interruptible(&wq);

out:
    up(&dev->sem);
    return ret;
}

long scull_ioctl(struct file *filep,
    unsigned int cmd, unsigned long arg)
{
    int ret = 0;
    int size = _IOC_SIZE(cmd);

    if (_IOC_TYPE(cmd) != SCULLC_IOC_MAGIC) {
        return -ENOTTY;
    }

    if (_IOC_NR(cmd) > SCULLC_IOC_MAXNR) {
        return -ENOTTY;
    }

    if (_IOC_DIR(cmd) & _IOC_READ) {
        ret = !access_ok(VERIFY_WRITE, (void*)arg, size);
    } else if (_IOC_DIR(cmd) & _IOC_WRITE) {
        ret = !access_ok(VERIFY_READ, (void*)arg, size);
    }

    if (ret) {
        return -EFAULT;
    }

    switch (cmd)
    {
    case SCULLC_IOCRESET:
        scull_qset = SCULL_QSET;
        scull_quantum = SCULL_QUANTUM;
        break;
    case SCULLC_IOCSQUANTUM:
        ret = get_user(scull_quantum, (u32 __user *)arg);
    default:
        return -ENOTTY;
        break;
    }

    return ret;
}
struct file_operations scull_fops = {
	.owner =    THIS_MODULE,
//	.llseek =   scull_llseek,
	.read =     scull_read,
	.write =    scull_write,
	.unlocked_ioctl =    scull_ioctl,
	.open =     scull_open,
	.release =  scull_release,
};

/*
 * Set up the char_dev structure for this device.
 */
static void scull_setup_cdev(Scull_Dev *dev, int index)
{
	int err, devno = MKDEV(scull_major, scull_minor + index);
    
	cdev_init(&dev->cdev, &scull_fops);
	dev->cdev.owner = THIS_MODULE;
	dev->cdev.ops = &scull_fops;
	err = cdev_add (&dev->cdev, devno, 1);
	/* Fail gracefully if need be */
	if (err)
		printk(KERN_NOTICE "Error %d adding scull%d", err, index);
    
    scull_device_fsys[index] = device_create(scull_class, NULL, devno, NULL, "scull%d", index);
    if (scull_device_fsys[index] < 0) {
        printk(KERN_WARNING "scull is not able to create device.\n");
    }
}


static int __init scull_init_module(void)
{
	int result, i;
	dev_t dev = 0;
#ifdef SCULLC_USE_PROC /* only when available */
    struct proc_dir_entry* proc_file;
#endif
    result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs,
            "scull");
    scull_major = MAJOR(dev);
	if (result < 0) {
		printk(KERN_WARNING "scull: can't get major %d\n", scull_major);
		return result;
	}
    scull_class = class_create(THIS_MODULE, "scull");
    if (IS_ERR(scull_class)) {
        printk(KERN_WARNING "scull is not create class.\n");
        return -EBUSY;
    }
    scull_device_fsys = kmalloc(scull_nr_devs * sizeof(struct device*), GFP_KERNEL);
    if (!scull_device_fsys) {
        class_destroy(scull_class);
        result = -ENOMEM;
        return -EBUSY;
    }

	scull_devices = kmalloc(scull_nr_devs * sizeof(Scull_Dev), GFP_KERNEL);
	if (!scull_devices) {
		result = -ENOMEM;
		goto fail;  /* Make this more graceful */
	}
	memset(scull_devices, 0, scull_nr_devs * sizeof(Scull_Dev));

   /* Initialize each device. */
	for (i = 0; i < scull_nr_devs; i++) {
		scull_devices[i].quantum = scull_quantum;
		scull_devices[i].qset = scull_qset;
        sema_init(&scull_devices[i].sem, 1);
		scull_setup_cdev(&scull_devices[i], i);
	}

#ifdef SCULLC_USE_PROC /* only when available */
    proc_file = proc_create("scullcmem", 0644, NULL, &scullc_proc_fops);
    if (!proc_file) {
        printk(KERN_ERR "proc file is fail to create.\n");
        goto fail;
    }
#endif

    printk(KERN_DEBUG "hello world.\n");
    return 0;

fail:
	scull_cleanup_module();
	return result;
}

module_init(scull_init_module);
module_exit(scull_cleanup_module);
